<template>
    <!-- 确认订单选择地址 -->
    <van-address-list
        v-if="action == 'select'"
        v-model="active"
        :list="list"
        default-tag-text="默认"
        @add="AddressAdd"
        @edit="AddressEdit"
        @select="CartSelect"
    />

    <!-- 从会员中心点击收获地址 -->
    <van-address-list
        v-else
        v-model="active"
        :list="list"
        default-tag-text="默认"
        @add="AddressAdd"
        @edit="AddressEdit"
        @select="AddressSelect"
    />
</template>

<script setup>
    const {proxy} = getCurrentInstance()

    // 接收关键词参数
    var query = proxy.$route.query.action ? proxy.$route.query.action : '';
    let action = ref(query)

    //收获地址列表
    let list = reactive([])
    let active = ref(0) //是否是默认地址

    //当页面一加载进来的时候就触发的挂载前生命周期钩子函数
    onBeforeMount(()=>{
        AddressList()
    })

    const AddressList = async () =>
    {
        //发起请求
        var result = await proxy.$POST({
            url: '/address/index',
            params: {
                busid: proxy.$business.value.id
            }
        })

        //要么是出错 要么没有数据
        if(result.code == 0)
        {
            proxy.$fail(result.msg)
            return false
        }

        result.data.map((item)=>{
            //找出默认的收获地址
            if(item.status == "1") active.value = item.id
            
            //重组收获地址结构
            list.push({
                id: item.id,
                name: item.consignee,
                tel: item.mobile,
                address: `${item.region_text} ${item.address}`,
                isDefault: item.status == '1' ? true : false
            })
        })
    }

    //收获地址添加
    const AddressAdd = async () => proxy.$router.push('/address/add')

    //收获地址编辑
    const AddressEdit = async (item) => proxy.$router.push({path: '/address/edit',query:{id: item.id}})

    //切换默认的收获地址
    const AddressSelect = async (item, index) => 
    {
        var result = await proxy.$POST({
            url: '/address/check',
            params: {
                busid: proxy.$business.value.id,
                id: item.id
            }
        })

        if(result.code == 0)
        {
            proxy.$fail(result.msg)
            return false
        }

        //成功就修改默认的状态
        list.map(value => {
            //把所有的地址全部修改为非默认地址
            value.isDefault = false

            //刚刚切换的地址 设置为默认的
            if(value.id == item.id) value.isDefault = true
        })
    }

    //确认订单切换地址
    const CartSelect = async (item,index) =>
    {
        item.region_text = item.address

        //将选择的收获地址存入到cookie中
        proxy.$cookies.set('address',item)

        proxy.$router.go(-1)
    }
</script>